package mycoffee.order.jsonhandler;

import java.io.File;
import java.util.ArrayList;

import mycoffee.order.model.Food;
import mycoffee.order.utils.ImageManager;
import mycoffee.order.xmlhandler.XmlConstants;

import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FoodsJsonHandler extends BaseJsonHandler {

	String folderPath;
	public FoodsJsonHandler( Context aContext ) {
		String packageName = aContext.getPackageName();
		folderPath = Environment.getExternalStorageDirectory() + "/Android/data/" + packageName + "/files/";
	}
	
	private void deleteAllImage() {
		File dir = new File(folderPath);
		if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i = 0; i < children.length; i++) {
	            new File(dir, children[i]).delete();
	        }
	    }
	}

	@Override
	protected void updateData(String result) {
		// TODO Auto-generated method stub
		Log.d("[FoodsJsonHandler]","In::updateData");
		try {
			int length = 0;
			JSONObject jsonObj = null;
			JSONArray jsonArr = new JSONArray( result );
			length = jsonArr.length();
			ArrayList<Food> foods = new ArrayList<Food>();
			Food food;
			ImageManager image = null;
			String subcategoryId = "";
			int id;
			String imagePath;
			this.deleteAllImage();
			for( int i = 0; i < length; i++ ) {	
				jsonObj = jsonArr.getJSONObject( i );
				food = new Food();
				// add info.
				id = jsonObj.getInt(XmlConstants.ID);
				food.setId(id);
				food.setName(jsonObj.getString(XmlConstants.NAME));
				food.setName_vi(jsonObj.getString(XmlConstants.NAME));
				food.setName_en(jsonObj.getString(XmlConstants.NAME));
				food.setName_de(jsonObj.getString(XmlConstants.NAME));
				food.setPrice(jsonObj.getDouble(XmlConstants.PRICE));
				subcategoryId = jsonObj.getString("subcategory");
				subcategoryId = subcategoryId.substring(1, subcategoryId.length() - 1 );
				//Log.d("[FoodsJsonHandler]", "subcategory = " + subcategoryId);
				food.setSubcategoryID(Integer.parseInt(subcategoryId));
				image = new ImageManager();
				image.DownloadFromUrl(jsonObj.getString("image"), folderPath, id+".png");
				imagePath = folderPath + id + ".png";
				Log.d("[FoodsJsonHandler]", "imagePath = " + imagePath);
				food.setImage(imagePath);
				foods.add(food);
			}
			dbCon.insertListFood(foods);
		} catch (Exception e) {
			Log.e("[FoodsJsonHandler]", e.getMessage(), e);
		}
		completed = true;
		Log.d("[FoodsJsonHandler]","Out::updateData");
	}

	@Override
	public boolean isSynz() {
		// TODO Auto-generated method stub
		boolean synz = false;
		if ( super.isSynz() || dbCon.getListFood().size() < 1 ) {
			synz = true;
		} else {
			synz = false;
		}
		
		return synz;
	}
	
}
